package com.business.java2cache.channel;

import com.business.java2cache.core.CacheConstans;
import com.business.java2cache.core.CacheManager;
import com.business.java2cache.redis.RedisCache;
import com.business.java2cache.redis.RedisPubSubListener;
import com.business.java2cache.util.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.BinaryJedisPubSub;
import redis.clients.jedis.Jedis;
import redis.clients.util.SafeEncoder;

/**
 * 缓存Redis SUB监听通道
 */
public class RedisCacheKit extends BaseCacheKit {

    private final static Logger log = LoggerFactory.getLogger(RedisCacheKit.class);
    private final static RedisCacheKit instance = new RedisCacheKit();
    private Thread thread_subscribe;

    /**
     * 单例方法
     *
     * @return 返回  单实例
     */
    public final static RedisCacheKit getInstance() {
        return instance;
    }

    /**
     * 初始化缓存通道并连接
     */
    private RedisCacheKit() throws CacheException {
        try {
            long ct = System.currentTimeMillis();
            //先初始化缓存redis实例
            CacheManager.initCacheProvider();
            //订阅消息频道
            thread_subscribe = new Thread(new Runnable() {
                @Override
                public void run() {
                    BinaryJedisPubSub redisPubSubListener = new RedisPubSubListener();
                    RedisCache redisCache = RedisCache.getInstance();
                    Jedis jedis = redisCache._getJedis();
                    /*Jedis jedis=redisCache.pool.getResource();*/
                    try {
                        jedis.subscribe(redisPubSubListener, SafeEncoder.encode(CacheConstans.redischannel));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread_subscribe.start();
            log.info("Connected to channel:" + ", time " + (System.currentTimeMillis() - ct) + " ms.");

        } catch (Exception e) {
            throw new CacheException(e);
        }
    }


}
